package com.example.wangzhenyu;
import com.example.wangzhenyu.api.ApiClient;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;


import com.example.wangzhenyu.api.ApiService;
import com.example.wangzhenyu.model.Chapter;
import com.example.wangzhenyu.model.ChapterResponse;
import com.example.wangzhenyu.model.Detail;
import com.example.wangzhenyu.model.DetailResponse;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MainViewModel extends AndroidViewModel {
    private MutableLiveData<List<Chapter>> chapters;
    private MutableLiveData<Detail> detail;

    public MainViewModel(@NonNull Application application) {
        super(application);
        chapters = new MutableLiveData<>();
        detail = new MutableLiveData<>();
    }

    public LiveData<List<Chapter>> getChapters(String appkey) {
        ApiService service = com.example.wangzhenyu.api.ApiClient.getClient().create(ApiService.class);
        Call<ChapterResponse> call = service.getChapters(appkey);
        call.enqueue(new Callback<ChapterResponse>() {
            @Override
            public void onResponse(Call<ChapterResponse> call, Response<ChapterResponse> response) {
                if (response.isSuccessful()) {
                    chapters.setValue(response.body().getResult());
                }
            }

            @Override
            public void onFailure(Call<ChapterResponse> call, Throwable t) {
                // Handle failure
            }
        });
        return chapters;
    }

    public LiveData<Detail> getDetail(String appkey, int detailid) {
        ApiService service = ApiClient.getClient().create(ApiService.class);
        Call<DetailResponse> call = service.getDetail(appkey, detailid);
        call.enqueue(new Callback<DetailResponse>() {
            @Override
            public void onResponse(Call<DetailResponse> call, Response<DetailResponse> response) {
                if (response.isSuccessful()) {
                    detail.setValue(response.body().getResult());
                }
            }

            @Override
            public void onFailure(Call<DetailResponse> call, Throwable t) {
                // Handle failure
            }
        });
        return detail;
    }
}